Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
Laravel 5.8: $bal->balance is getting null

I want to get a value of balance column from a pivot table called user_wallet which goes like this:

enter image description here

So I wrote this at the Controller:

$bal = Wallet::with("users")->whereHas('users', function ($query) use ($wallet_id, $user_id) {
    $query->where('wallet_id', $wallet_id);
    $query->where('user_id', $user_id);
})->first();

But when I do dd($bal->balance), I get null!

So why is that? How can I get the balance value based on user_id and wallet_id properly?

Here is also the relationships between User model and Wallet model:

User.php

public function wallets()
{
    return $this->belongsToMany(Wallet::class, 'user_wallet', 'user_id', 'wallet_id')->withPivot('balance');
}

Wallet.php

public function users()
{
    return $this->belongsToMany(User::class, 'user_wallet', 'wallet_id', 'user_id');
}

I would really appreciate any idea or suggestion from you guys...

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Your query is supposed to be like below. Becuase the relation you're making is with users table not user_wallet.

$bal = Wallet::with("users")
    ->whereHas('users', function ($query) use ($user_id) {
        $query->where('id',$user_id);
    })
    ->where('id', $wallet_id)
    ->first();

You can make a simple query as well:

$bal = DB::table('user_wallet')
    ->where('wallet_id', $wallet_id)
    ->where('user_id', $user_id)
    ->first();

if (!empty($bal)) {
    $balance = $bal->balance;
}
over 4 years ago · Santiago Trujillo Report

0

Since it is a many to many relationship, for getting the pivot table you loop like below:

@foreach($bal as $key => $value)
    {{$value->pivot->balance}}
@endforeach

or if it is a single item then you can do like:

$user = $bal->users()->first();

$user->pivot->balance;

or

$user = $bal->users->first();

$user->pivot->balance;

if still need directly then, as suggested by @Dilip Hirapara answer.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!